package com.tunnel.home.common;

import java.time.Duration;
import java.util.Properties;

import org.axe.interface_.mvc.Listener;
import org.axe.util.LogUtil;
import org.axe.util.PropsUtil;

import com.tunnel.common.util.StringUtil;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.RedisURI.Builder;

public class RedisListener implements Listener{
	@Override
	public int index() {
		return 1;
	}
	
    
    @Override
    public void init() throws Exception {
    	try {
    		Properties redisProps = PropsUtil.loadProps("redis.properties");
    		String host = PropsUtil.getString(redisProps, "host");
    		int port = PropsUtil.getInt(redisProps, "port");
    		String password = PropsUtil.getString(redisProps, "password");
    		int database = PropsUtil.getInt(redisProps, "db");
    		
    		Builder redisBuilder = RedisURI.builder()                    // <1> 创建单机连接的连接信息
    	            .withHost(host)
    	            .withPort(port);
    		if(StringUtil.isNotEmpty(password)){
    			redisBuilder = redisBuilder.withPassword(password);
    		}
    		RedisURI redisUri = redisBuilder.withDatabase(database)
								            .withTimeout(Duration.ofSeconds(10))
								            .build();
    	            
    	    RedisClient redisClient = RedisClient.create(redisUri);   // <2> 创建客户端
    	    RedisUtil.setConnection(redisClient.connect());      // <3> 创建线程安全的连接
        } catch (Exception e) {
			LogUtil.error(e);
			System.exit(1);
        }
    }
    
}
